﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Customize.Excel.Import
{
    public class ExcelImportAttribute : ValidationAttribute
    {
        /// <summary>
        /// Excel表头的内容
        /// </summary>
        public string HeaderText { get; set; }

        /// <summary>
        /// 数据字段名
        /// </summary>
        [DisplayName()]
        public string FieldName { get; set; }

        /// <summary>
        /// 允许的字符,允许使用【, ， ; ； 、 / |$】分割
        /// </summary>
        public string AllowText { get; set; }

        /// <summary>
        /// 将Excel值转换为数据的特殊方法  
        /// </summary>
        public Func<string, object> Convert { get; set; }

        public ExcelImportAttribute()
        {
        }
        public ExcelImportAttribute(string excelText, string fieldName)
            : this(excelText, fieldName, false, null)
        {
        }
        public ExcelImportAttribute(string excelText, string fieldName, bool require)
            : this(excelText, fieldName, require, null)
        {
        }

        public ExcelImportAttribute(string excelText, string fieldName, Func<string, object> cellConvert)
            : this(excelText, fieldName, false, cellConvert)
        {
        }
        public ExcelImportAttribute(string excelText, string fieldName, bool required, Func<string, object> cellConvert)
        {
            if (string.IsNullOrEmpty(excelText))
                throw new ArgumentNullException("excelText");
            if (string.IsNullOrEmpty(fieldName))
                throw new ArgumentNullException("fieldName");

            this.HeaderText = excelText;
            this.FieldName = fieldName;

            this.Convert = cellConvert;
        }


        public override bool IsValid(object value)
        {
            if (string.IsNullOrEmpty(AllowText)) return true;

            var allowOptions = AllowText.Split(',', '，', ';', '；', '、', '/', '|', '$');
            return allowOptions.Contains(value);
        }
        public object Clone()
        {
            var Formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
            MemoryStream stream = new MemoryStream();
            Formatter.Serialize(stream, this);
            stream.Position = 0;
            object clonedObj = Formatter.Deserialize(stream);
            stream.Close();
            return clonedObj;
        }

    }
}
